<template>
	<view class="container">
		<view
			class="box"
			:style="{
				transform: coverTransform,
				transition: coverTransition
			}"
			@touchstart="handleTouchstart"
			@touchmove="handleTouchmove"
			@touchend="handleTouchend"
		>
			<view 
				class="prompt-box"
				:style="{
					height: `${downHeight}px`,
					marginTop: `-${downHeight}px`
				}"
			>
				{{text}}
			</view>
			<slot></slot>
		</view>
	</view>
</template>

<script>
	let startY = 0,
			moveY = 0,
			pageAtTop = true;
			
	export default {
		props: {
			loading: Boolean
		},
		model: {
			prop: "loading",
			event: "setload",
		},
		data() {
			return {
				coverTransform: 'translateY(0px)',
				coverTransition: '0s',
				moving: false,
				downHeight: 40,
				text: "释放即可刷新"
			};
		},
		watch: {
			loading(val) {
				console.log("loading发生了变化", val)
				// this.handleRestore()
			}
		},
		methods: {
			// 手指触摸开始
			handleTouchstart(e) {
				if(this.moving === true){
					return;
				}
				this.coverTransition = 'transform .3s linear';
				startY = e.touches[0].clientY;
				this.text = "释放即可刷新"
			},
			// 手指在节点上移动
			handleTouchmove(e) {
				moveY = e.touches[0].clientY;
				let moveDistance = moveY - startY;
				if(moveDistance < 0) {
					this.moving = false;
					return;
				}
				// 加载中
				this.moving = true;
				if(moveDistance >= this.downHeight && moveDistance < 100) {
					moveDistance = this.downHeight;
				}
				if(moveDistance > 0 && moveDistance <= 110) {
					this.coverTransform = `translateY(${moveDistance}px)`;
				}
			},
			// 手指离开节点
			handleTouchend() {
				if(this.moving === false) {
					return;
				}
				this.coverTransition = 'transform .5s linear';
				this.coverTransform = `translateY(${this.downHeight}px)`;
				this.$emit("setload", true)
				this.$emit("refresh")
				this.text = "加载中..."
				setTimeout(()=> this.handleRestore(),1000)
			},
			
			// 复原
			handleRestore() {
				this.text = ""
				this.moving = false;
				this.coverTransition = 'transform .3s linear';
				this.coverTransform = `translateY(0px)`;
			}
		}
	}
</script>

<style lang="scss" scoped>
.container{
	.box{
		
	}
	.prompt-box{
		box-sizing: border-box;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #999;
		font-size: 30rpx;
	}
}
</style>
